package com.ddw.wotcg.server.controllers;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ddw.wotcg.server.utils.TemplateHelper;

import freemarker.template.Configuration;

@SuppressWarnings("serial")
public abstract class ControllerBase extends HttpServlet {
	
	protected Configuration config;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.request = req;
		this.response = resp;
		
		// Parse the action from the url
		final String action = parseAction(req);
		
		try {
			final Method method = this.getClass().getMethod(action);
			try {
				method.invoke(this, new Object[0]);
			} catch (final IllegalArgumentException e) {
				e.printStackTrace();
			} catch (final IllegalAccessException e) {
				e.printStackTrace();
			} catch (final InvocationTargetException e) {
				e.printStackTrace();
			}
		} catch (final SecurityException e) {
			e.printStackTrace();
		} catch (final NoSuchMethodException e) {
			try {
				errorPage("Page could not be accessed, not found!");
				e.printStackTrace();
			} catch (final ServletException e2) {
				e2.printStackTrace();
			}
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	public void errorPage(String message) throws IOException, ServletException {
		final Map<String, Object> root = new HashMap<String, Object>();
		TemplateHelper.appendPageData(root, "Oops");
		TemplateHelper.callTemplate(this.config, this.response,
				"/layout/error.ftl", root);
	}
	
	@Override
	public void init() throws ServletException {
		this.config = new Configuration();
		this.config.setServletContextForTemplateLoading(getServletContext(),
				"WEB-INF/views");
		this.config.setDefaultEncoding("UTF-8");
		this.config.setNumberFormat("0.######");
	}
	
	private String parseAction(HttpServletRequest req) {
		final String action = req.getPathInfo();
		if (action == null) {
			return "index";
		}
		final String[] parts = action.split("/");
		if (parts.length > 1) {
			return parts[1];
		} else {
			return "index";
		}
	}
	
}
